package com.bestcem.xm.award.grpc.service;


import com.bestcem.bp.grpc.v1.base.FileInfo;
import com.bestcem.xm.award.constant.RedPacketConstant;
import com.bestcem.xm.award.grpc.service.param.redpacket.WinDetailListParam;
import com.bestcem.xm.award.grpc.v1.services.*;
import com.bestcem.xm.award.service.RedPacketDisplayService;
import com.bestcem.xm.award.service.dto.*;
import com.bestcem.xm.common.core.domain.web.RpcStatusResult;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.sign.grpc.core.GrpcTemplate;
import com.bestcem.xm.common.core.uitls.DateUtil;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author xa.zhang <xa.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2021/6/30 13:40
 * @desc
 */
@GrpcService
public class RedPacketDisplayGrpcService extends RedPacketServiceGrpc.RedPacketServiceImplBase {

    @Resource
    private RedPacketDisplayService redPacketService;

    @Resource
    private GrpcTemplate grpcTemplate;

    private final BigDecimal bigDecimal100 = new BigDecimal(RedPacketConstant.INT100);


    /**
     * 查看红包详情页面中的 获取红包总览
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void getRedPacketStats(GetRedPacketStatsRequest request,
                                  StreamObserver<GetRedPacketStatsResponse> responseObserver) {
        // 校验参数
        if (StringUtils.isBlank(request.getId())) {
            GetRedPacketStatsResponse.Builder builder = GetRedPacketStatsResponse.newBuilder();
            builder.setStatus(RpcStatusResult.error("缺少参数"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<RedPacketStatsDTO> serviceResult = redPacketService.getRedPacketStats(request.getId());

        // 数据转换
        GetRedPacketStatsResponse.Builder builder = GetRedPacketStatsResponse.newBuilder();
        RedPacketStats.Builder data = RedPacketStats.newBuilder();
        if (serviceResult.isSuccess()) {

            builder.setStatus(RpcStatusResult.success());
            convertToRedPacketStatsData(data, serviceResult.getData());
            builder.setRedPacketStats(data);
        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 数据转换
     *
     * @param data
     * @param bonusOverviewDto
     */
    private void convertToRedPacketStatsData(RedPacketStats.Builder data, RedPacketStatsDTO bonusOverviewDto) {
        data.setTotalCount(bonusOverviewDto.getTotalCount());
        data.setSentCount(bonusOverviewDto.getSentCount());
        data.setSentAmount(convertAmountToInt(bonusOverviewDto.getSentAmount()));
        data.setTotalAmount(convertAmountToInt(bonusOverviewDto.getTotalAmount()));
        data.setWaitAmount(convertAmountToInt(bonusOverviewDto.getWaitAmount()));
        data.setWaitCount(bonusOverviewDto.getWaitCount());
    }

    private int convertAmountToInt(BigDecimal bigDecimal) {
        if (bigDecimal == null) {
            return 0;
        }
        return bigDecimal.multiply(bigDecimal100).intValue();
    }

    /**
     * 查看红包详情页面中的 获取投放数据统计
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void getDeliverStats(GetDeliverStatsRequest request,
                                StreamObserver<GetDeliverStatsResponse> responseObserver) {
        // 校验参数
        if (StringUtils.isBlank(request.getId())) {
            GetDeliverStatsResponse.Builder builder = GetDeliverStatsResponse.newBuilder();
            builder.setStatus(RpcStatusResult.error("缺少参数"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<List<DeliverDetailDTO>> serviceResult = redPacketService.getDeliverDetail(request.getId());

        // 数据转换
        GetDeliverStatsResponse.Builder builder = GetDeliverStatsResponse.newBuilder();

        if (serviceResult.isSuccess()) {

            List<DeliverDetailDTO> list = serviceResult.getData();
            builder.setStatus(RpcStatusResult.success());

            for (DeliverDetailDTO deliverDetailDto : list) {
                if (deliverDetailDto.getSentAmount() == null) {
                    deliverDetailDto.setSentAmount(BigDecimal.ZERO);
                }
                DeliverDetail.Builder detailBuilder = DeliverDetail.newBuilder();
                detailBuilder.setName(deliverDetailDto.getName() != null ? deliverDetailDto.getName() : "");
                detailBuilder.setSentCount(deliverDetailDto.getSentCount() != null ? deliverDetailDto.getSentCount() : 0);
                detailBuilder.setSentAmount(convertAmountToInt(deliverDetailDto.getSentAmount()));

                builder.addDetails(detailBuilder);
            }
        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();


    }


    /**
     * 查看红包详情页面中的中奖名单 投放名称列表获取
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void listDeliverNames(ListDeliverNamesRequest request,
                                 StreamObserver<ListDeliverNamesResponse> responseObserver) {
        // 校验参数
        if (StringUtils.isBlank(request.getId())) {
            ListDeliverNamesResponse.Builder builder = ListDeliverNamesResponse.newBuilder();
            builder.setStatus(RpcStatusResult.error("缺少参数"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<List<String>> serviceResult = redPacketService.getDeliverNameList(request.getId());

        // 数据转换
        ListDeliverNamesResponse.Builder builder = ListDeliverNamesResponse.newBuilder();

        if (serviceResult.isSuccess()) {
            builder.addAllNames(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());

        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }

        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 查看红包详情页面中的中奖名单 中奖名单列表
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void listWinDetails(ListWinDetailsRequest request,
                               StreamObserver<ListWinDetailsResponse> responseObserver) {

        ServiceResult<WinDetailDTO> serviceResult = redPacketService.getWinDetailList(WinDetailListParam.createFromRequest(request));
        ListWinDetailsResponse.Builder builder = ListWinDetailsResponse.newBuilder();


        if (serviceResult.isSuccess()) {
            WinDetailDTO winDetailDto = serviceResult.getData();

            builder.setStatus(RpcStatusResult.success());

            builder.setTotal(winDetailDto.getTotal());

            // 数据转换
            winDetailDto.getList().stream().forEach(item -> {

                WinDetail.Builder rowBuilder = WinDetail.newBuilder();

                rowBuilder.setAmount(item.getAmount() == null ? 0 : item.getAmount());
                rowBuilder.setDeliverName(item.getDeliverName() == null ? "" : item.getDeliverName());
                rowBuilder.setSeq(item.getSeq() == null ? 0 : item.getSeq().intValue());
                rowBuilder.setDeliverChannelValue(item.getDeliverChannel() == null ? 0 : item.getDeliverChannel());
                rowBuilder.setStatusValue(item.getStatus() == null ? 0 : item.getStatus());
                if (item.getSendTime() != null) {
                    //导出正常，但是grpc转换后传给前端会少8小时，所以这里加8小时
                    rowBuilder.setSendTime(DateUtil.getTimestamp(item.getSendTime()));
                }

                builder.addDetails(rowBuilder.build());
            });

        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * 查看红包详情页面中的中奖名单 获取中奖人数
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void countWinner(CountWinnerRequest request,
                            StreamObserver<CountWinnerResponse> responseObserver) {

        // 校验参数
        if (StringUtils.isBlank(request.getId())) {
            CountWinnerResponse.Builder builder = CountWinnerResponse.newBuilder();
            builder.setStatus(RpcStatusResult.error("缺少参数"));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        ServiceResult<Integer> serviceResult = redPacketService.getWinCount(request.getId());

        CountWinnerResponse.Builder builder = CountWinnerResponse.newBuilder();
        // 数据转换
        if (serviceResult.isSuccess()) {
            builder.setWinCount(serviceResult.getData());
            builder.setStatus(RpcStatusResult.success());

        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    /**
     * 查看红包详情页面中的 导出中奖名单 RedPacketWinExportResponse
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void exportRedPacketWin(ExportRedPacketWinRequest request,
                                   StreamObserver<ExportRedPacketWinResponse> responseObserver) {

        ServiceResult<FileInfoDTO> serviceResult = redPacketService.exportWinDetailList(WinDetailListParam.createFromExportRequest(request));
        ExportRedPacketWinResponse.Builder builder = ExportRedPacketWinResponse.newBuilder();

        // 数据转换
        if (serviceResult.isSuccess()) {
            FileInfoDTO fileInfoDTO = serviceResult.getData();

            builder.setStatus(RpcStatusResult.success());

            FileInfo.Builder fileInfoBuilder = FileInfo.newBuilder();
            fileInfoBuilder.setId(fileInfoDTO.getId());
            fileInfoBuilder.setName(fileInfoDTO.getName());
            fileInfoBuilder.setUrl(fileInfoDTO.getUrl());

            builder.setFileInfo(fileInfoBuilder.build());

        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    /**
     * 二维码后面的红包抽奖入口页，生成requestId,sig
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void getRedPacketDraw(GetRedPacketDrawRequest request,
                                 StreamObserver<GetRedPacketDrawResponse> responseObserver) {

        GetRedPacketDrawResponse.Builder builder = GetRedPacketDrawResponse.newBuilder();
        // 验签
        ServiceResult checkSignResult = grpcTemplate.checkSign(request);
        if (!checkSignResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(checkSignResult.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }
        ServiceResult<RedPacketEntryDTO> serviceResult = redPacketService.getRedPacketDraw(request.getId(), request.getCode(), request.getRequestId());

        // 数据转换
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());

            RedPacketEntryDTO redPacketEntryDto = serviceResult.getData();

            GetRedPacketInfo.Builder infoBuilder = GetRedPacketInfo.newBuilder();

            infoBuilder.setId(redPacketEntryDto.getAwardId());
            infoBuilder.setRequestId(redPacketEntryDto.getRequestId());
            infoBuilder.setDisplayLogoId(redPacketEntryDto.getDisplayLogoId() == null ? "" : redPacketEntryDto.getDisplayLogoId());
            infoBuilder.setDisplayLogoPath(redPacketEntryDto.getDisplayLogoPath() == null ? "" : redPacketEntryDto.getDisplayLogoPath());
            infoBuilder.setDisplayName(redPacketEntryDto.getDisplayName() == null ? "" : redPacketEntryDto.getDisplayName());

            builder.setInfo(infoBuilder.build());

        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();

    }

    /**
     * 二维码后面的红包抽奖页 红包抽奖
     *
     * @param request          请求参数
     * @param responseObserver 输出流
     */
    @Override
    public void drawRedPacket(DrawRedPacketRequest request,
                              StreamObserver<DrawRedPacketResponse> responseObserver) {

        DrawRedPacketResponse.Builder builder = DrawRedPacketResponse.newBuilder();

        // 验签
        ServiceResult checkSignResult = grpcTemplate.checkSign(request);
        if (!checkSignResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.error(checkSignResult.getMsg()));
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
            return;
        }

        ServiceResult<Integer> serviceResult = redPacketService.drawRedPacket(request.getRequestId(), request.getId());

        // 数据转换
        if (serviceResult.isSuccess()) {
            builder.setStatus(RpcStatusResult.success());
            builder.setWinAmount(serviceResult.getData() == null ? 0 : serviceResult.getData());
        } else {
            builder.setStatus(RpcStatusResult.error(serviceResult.getMsg()));
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


}
